package com.zy.nettypoject.netty.nio;

import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel open = ServerSocketChannel.open();
        open.bind(new InetSocketAddress(8099));
        open.configureBlocking(false);//非阻塞
        List<SocketChannel> channels = new ArrayList<>();
        ByteBuffer allocate = ByteBuffer.allocate(16);
        while (true) {
            try {
                SocketChannel channel = open.accept();
                if (!Objects.isNull(channel)) {
                    log.info("链接成功..."+channel);
                    channels.add(channel);
                }
                for (SocketChannel c : channels) {
                    try {
                        c.configureBlocking(false);
//                        System.out.println("读取数据之前");
                        int read = c.read(allocate);
                        if (read > 0){
                            System.out.println("读取数据...");
                            allocate.flip();
                            printf(allocate);
                            allocate.clear();
                        }
                    } catch (IOException e) {
                    }
                }
            } catch (Exception e) {
//                System.out.println("链接丢失");
            }
        }
    }

    public static void printf(ByteBuffer buf) {
        while (true) {
            if (!buf.hasRemaining()) break;
            byte b = buf.get();
            System.out.print((char) b);
        }
        System.out.println();
    }
}
